import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { View, Text, Button, Input, Image } from '@tarojs/components'
import { Cell, Dialog, Toast } from '@taroify/core'
import { ClockOutlined, ShieldOutlined, Paid } from '@taroify/icons'
import { loginFun, isLoggedIn, getCurrentOpenId } from '@/utils/auth'
import './index.scss'

const MfaPage = () => {
  const [isBound, setIsBound] = useState(false)
  const [qrCode, setQrCode] = useState('')
  const [secret, setSecret] = useState('')
  const [verificationCode, setVerificationCode] = useState('')
  const [showQrDialog, setShowQrDialog] = useState(false)
  const [toastConfig, setToastConfig] = useState({ open: false, message: '', type: 'success' })

  useEffect(() => {
    checkLoginStatus()
  }, [])

  // 获取登录状态，检查是否已绑定MFA
  const checkLoginStatus = async () => {
    try {
      Taro.showLoading({ title: '加载中...' })

      // 先检查是否已登录
      let openId = null
      if (isLoggedIn()) {
        openId = getCurrentOpenId()
        console.log('已有登录状态，使用缓存openId:', openId)
      } else {
        // 未登录或状态过期，重新登录
        const loginResult = await loginFun()
        if (loginResult.success && loginResult.openId) {
          openId = loginResult.openId
        } else {
          Taro.hideLoading()
          showToast('登录失败，请重试', 'error')
          return
        }
      }

      // 检查用户是否已绑定MFA
      const checkResult = await Taro.cloud.callFunction({
        name: 'checkMfaStatus',
        data: {
          openId
        }
      })

      if (checkResult && checkResult.result) {
        setIsBound(checkResult.result.isBound)
      }

      Taro.hideLoading()
    } catch (error) {
      console.error('检查登录状态失败:', error)
      Taro.hideLoading()
      showToast('获取登录状态失败', 'error')
    }
  }

  // 绑定MFA
  const handleBindMfa = async () => {
    try {
      // 先检查是否已登录
      let openId = null
      if (isLoggedIn()) {
        openId = getCurrentOpenId()
      } else {
        Taro.showLoading({ title: '获取登录信息...' })
        const loginResult = await loginFun()
        Taro.hideLoading()

        if (!loginResult.success || !loginResult.openId) {
          showToast('请先登录', 'error')
          return
        }
        openId = loginResult.openId
      }

      Taro.showLoading({ title: '生成密钥中...' })
      // 调用云函数生成MFA密钥
      const result = await Taro.cloud.callFunction({
        name: 'generateMfaSecret',
        data: {
          openId
        }
      })

      if (result && result.result && result.result.secret && result.result.qrCodeUrl) {
        setSecret(result.result.secret)
        setQrCode(result.result.qrCodeUrl)
        setShowQrDialog(true)
        Taro.hideLoading()
      } else {
        Taro.hideLoading()
        showToast('生成密钥失败', 'error')
      }
    } catch (error) {
      console.error('绑定MFA失败:', error)
      Taro.hideLoading()
      showToast('绑定MFA失败', 'error')
    }
  }

  // 验证并完成绑定
  const completeBinding = async () => {
    if (!verificationCode || verificationCode.length !== 6) {
      showToast('请输入6位验证码', 'error')
      return
    }

    try {
      // 先检查是否已登录
      let openId = null
      if (isLoggedIn()) {
        openId = getCurrentOpenId()
      } else {
        const loginResult = await loginFun()
        if (!loginResult.success || !loginResult.openId) {
          showToast('登录状态已过期，请重新登录', 'error')
          return
        }
        openId = loginResult.openId
      }

      Taro.showLoading({ title: '验证中...' })

      console.log('提交验证数据:', {
        openId,
        secret,
        code: verificationCode
      })

      // 调用云函数验证码并完成绑定
      const result = await Taro.cloud.callFunction({
        name: 'verifyAndBindMfa',
        data: {
          openId,
          secret,
          code: verificationCode
        }
      })

      Taro.hideLoading()
      console.log('验证结果:', result)

      if (result && result.result && result.result.success) {
        showToast('MFA绑定成功', 'success')
        setIsBound(true)
        setShowQrDialog(false)
        setVerificationCode('')
      } else {
        const errorMsg = result?.result?.message || '验证码无效，请重试'
        console.log('验证失败原因:', errorMsg, result)
        showToast(errorMsg, 'error')
      }
    } catch (error) {
      console.error('验证MFA失败:', error)
      Taro.hideLoading()
      showToast('验证失败: ' + (error.message || '未知错误'), 'error')
    }
  }

  // 验证MFA
  const verifyMfa = async () => {
    if (!verificationCode || verificationCode.length !== 6) {
      showToast('请输入6位验证码', 'error')
      return
    }

    try {
      // 先检查是否已登录
      let openId = null
      if (isLoggedIn()) {
        openId = getCurrentOpenId()
      } else {
        const loginResult = await loginFun()
        if (!loginResult.success || !loginResult.openId) {
          showToast('登录状态已过期，请重新登录', 'error')
          return
        }
        openId = loginResult.openId
      }

      Taro.showLoading({ title: '验证中...' })

      // 调用云函数验证MFA码
      const result = await Taro.cloud.callFunction({
        name: 'verifyMfa',
        data: {
          openId,
          code: verificationCode
        }
      })

      Taro.hideLoading()

      if (result && result.result && result.result.success) {
        showToast('验证成功', 'success')
        setVerificationCode('')
      } else {
        showToast('验证码无效或已过期', 'error')
      }
    } catch (error) {
      console.error('验证MFA失败:', error)
      Taro.hideLoading()
      showToast('验证失败', 'error')
    }
  }

  // 解绑MFA
  const unbindMfa = async () => {
    Taro.showModal({
      title: '确认解绑',
      content: '确定要解除MFA二次验证吗？解绑后将降低账户安全性',
      success: async (res) => {
        if (res.confirm) {
          try {
            // 先检查是否已登录
            let openId = null
            if (isLoggedIn()) {
              openId = getCurrentOpenId()
            } else {
              const loginResult = await loginFun()
              if (!loginResult.success || !loginResult.openId) {
                showToast('登录状态已过期，请重新登录', 'error')
                return
              }
              openId = loginResult.openId
            }

            Taro.showLoading({ title: '解绑中...' })

            // 调用云函数解绑MFA
            const result = await Taro.cloud.callFunction({
              name: 'unbindMfa',
              data: {
                openId
              }
            })

            Taro.hideLoading()

            if (result && result.result && result.result.success) {
              showToast('MFA已解绑', 'success')
              setIsBound(false)
            } else {
              showToast('解绑失败', 'error')
            }
          } catch (error) {
            console.error('解绑MFA失败:', error)
            Taro.hideLoading()
            showToast('解绑失败', 'error')
          }
        }
      }
    })
  }

  // 显示Toast提示
  const showToast = (message, type = 'success') => {
    setToastConfig({
      open: true,
      message,
      type
    })

    setTimeout(() => {
      setToastConfig({ ...toastConfig, open: false })
    }, 2000)
  }

  return (
    <View className='mfa-page'>
      <View className='header'>
        <Paid size='60' color='#4f46e5' />
        <Text className='title'>MFA二次验证</Text>
        <Text className='description'>通过双重认证提高您的账户安全性</Text>
      </View>

      <View className='content'>
        {!isBound ? (
          <View className='bind-section'>
            <View className='info-card'>
              <ShieldOutlined size='48' color='#4f46e5' />
              <Text className='info-title'>增强账户安全</Text>
              <Text className='info-text'>
                绑定MFA后，您将需要输入手机验证器生成的动态码作为第二重验证，有效防止账户被盗用。
              </Text>
            </View>

            <Button className='action-btn' type='primary' onClick={handleBindMfa}>
              绑定MFA验证器
            </Button>
          </View>
        ) : (
          <View className='verify-section'>
            <View className='status-card'>
              <ShieldOutlined size='48' color='#4f46e5' />
              <Text className='status-title'>MFA已启用</Text>
              <Text className='status-text'>您的账户已开启MFA二次验证保护</Text>
            </View>

            <Cell.Group inset title='验证MFA' className='verify-group'>
              <Cell>
                <Input
                  className='code-input'
                  type='number'
                  maxlength={6}
                  placeholder='请输入6位验证码'
                  value={verificationCode}
                  onInput={(e) => setVerificationCode(e.detail.value)}
                />
              </Cell>
            </Cell.Group>

            <Button className='action-btn' type='primary' onClick={verifyMfa}>
              验证
            </Button>

            <Button className='action-btn unbind-btn' onClick={unbindMfa}>
              解绑MFA
            </Button>
          </View>
        )}
      </View>

      {/* QR码对话框 */}
      <Dialog open={showQrDialog} onClose={() => setShowQrDialog(false)}>
        <Dialog.Header>扫描二维码</Dialog.Header>
        <Dialog.Content>
          <View className='qr-container'>
            <Image className='qr-code' src={qrCode} showMenuByLongpress mode='aspectFit' />
            <Text
              className='secret-key'
              onClick={() => {
                Taro.setClipboardData({
                  data: secret,
                  success: () => {
                    showToast('密钥已复制', 'success')
                  }
                })
              }}>
              密钥: {secret}
            </Text>
            <Text className='qr-tip'>
              请使用Google Authenticator或其他TOTP验证器扫描二维码或手动输入密钥{' '}
              <Text className='hint-link'>前往TOTP生成器</Text>
            </Text>
          </View>

          <View className='verify-container'>
            <Text className='verify-label'>输入验证器生成的6位验证码完成绑定</Text>
            <Input
              className='verify-input'
              type='number'
              maxlength={6}
              placeholder='6位验证码'
              value={verificationCode}
              onInput={(e) => setVerificationCode(e.detail.value)}
            />
          </View>
        </Dialog.Content>
        <Dialog.Actions>
          <Button onClick={() => setShowQrDialog(false)} className='cancel-btn'>
            取消
          </Button>
          <Button type='primary' onClick={completeBinding} className='confirm-btn confirm-bg'>
            验证并绑定
          </Button>
        </Dialog.Actions>
      </Dialog>

      {/* Toast提示 */}
      <Toast
        open={toastConfig.open}
        type={toastConfig.type}
        onClose={() => setToastConfig({ ...toastConfig, open: false })}>
        {toastConfig.message}
      </Toast>
    </View>
  )
}

export default MfaPage
